<template>
  <div class="work-team-page">
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchForm" label-width="80">
        <el-form-item label="班组名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入班组名称"
            clearable
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="班组类型">
          <el-select
            v-model="searchForm.typeid"
            placeholder="请选择类型"
            clearable
            filterable
            style="width: 220px"
            :loading="teamTypeLoading"
          >
            <el-option
              v-for="item in teamTypeOptions"
              :key="item.id"
              :label="item.typename"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <div class="table-toolbar">
        <el-button type="success" @click="openCreateDialog">新增班组</el-button>
        <el-button
          type="danger"
          :disabled="!selectedIds.length"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="teamnumber" label="班组编码" min-width="120" />
        <el-table-column prop="teamname" label="班组名称" min-width="140" />
        <el-table-column
          prop="typename"
          label="班组类型"
          min-width="140"
          show-overflow-tooltip
        />
        <el-table-column prop="fzr" label="负责人" min-width="120" />
        <el-table-column prop="status" label="状态" min-width="100" />
        <el-table-column
          prop="desc"
          label="备注"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="openEditDialog(row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.totalCount"
          v-model:current-page="pagination.pageindex"
          v-model:page-size="pagination.pagesize"
          :page-sizes="[10, 20, 30, 50]"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <el-dialog
      draggable
      v-model="dialogVisible"
      :title="dialogTitle"
      width="520px"
      destroy-on-close
    >
      <el-form
        ref="dialogFormRef"
        :model="dialogForm"
        :rules="dialogRules"
        label-width="90"
      >
        <el-form-item label="班组编码" prop="teamnumber">
          <el-input v-model="dialogForm.teamnumber" placeholder="请输入班组编码" />
        </el-form-item>
        <el-form-item label="班组名称" prop="teamname">
          <el-input v-model="dialogForm.teamname" placeholder="请输入班组名称" />
        </el-form-item>
        <el-form-item label="班组类型" prop="teamtypeid">
          <el-select
            v-model="dialogForm.teamtypeid"
            placeholder="请选择班组类型"
            filterable
            :loading="teamTypeLoading"
          >
            <el-option
              v-for="item in teamTypeOptions"
              :key="item.id"
              :label="item.typename"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人" prop="fzr">
          <div class="fzr-select-row">
            <el-input
              v-model="dialogForm.fzr"
              placeholder="请选择负责人"
              readonly
              @click="openUserDialog"
            />
            <el-button type="primary" @click="openUserDialog" style="margin-left: 8px">
              选择
            </el-button>
            <el-button
              v-if="dialogForm.fzr"
              text
              type="danger"
              @click="clearSelectedUser"
            >
              清除
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="dialogForm.status" placeholder="请选择状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="desc">
          <el-input
            v-model="dialogForm.desc"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="saving" @click="handleSubmit">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>

  <el-dialog
    draggable
    v-model="userDialogVisible"
    title="选择负责人"
    width="780px"
  >
    <div class="user-picker">
      <div class="user-picker-header">
        <div class="selected-users">
          <span class="label">已选择：</span>
          <el-tag
            v-if="selectedUserName"
            type="success"
            closable
            @close="selectedUserName = ''"
          >
            {{ selectedUserName }}
          </el-tag>
          <span v-else class="placeholder">暂无</span>
        </div>
        <el-input
          v-model="userSearchKeyword"
          placeholder="请输入用户名"
          clearable
          :prefix-icon="Search"
          style="width: 260px"
        />
      </div>
      <div class="user-picker-body">
        <div class="user-picker-tree">
          <el-scrollbar>
            <el-tree
              v-loading="organTreeLoading"
              :data="organTree"
              node-key="value"
              default-expand-all
              highlight-current
              @node-click="handleOrganNodeClick"
            />
          </el-scrollbar>
        </div>
        <div class="user-picker-list">
          <el-scrollbar height="320px">
            <el-empty
              v-if="!filteredUserList.length && !userListLoading"
              description="请选择组织或无成员"
            />
            <div v-else>
              <el-skeleton
                :loading="userListLoading"
                animated
                :rows="5"
              >
                <el-radio-group
                  v-model="selectedUserName"
                  class="user-radio-group"
                >
                  <el-radio
                    v-for="user in filteredUserList"
                    :key="user.userName"
                    :label="user.userName"
                  >
                    {{ user.userName }}
                  </el-radio>
                </el-radio-group>
              </el-skeleton>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </div>
    <template #footer>
      <el-button @click="userDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleUserConfirm" :disabled="!selectedUserName">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed } from 'vue'
import https from '@/Http/http'
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules
} from 'element-plus'
import { Search } from '@element-plus/icons-vue'

interface WorkTeam {
  id: number
  teamname: string
  teamnumber: string
  teamtypeid: number
  typename?: string
  fzr: string
  status: string
  desc: string
}

interface TeamTypeOption {
  id: number
  typename: string
}

interface OrganNode {
  value: number
  label: string
  children?: OrganNode[]
}

interface UserItem {
  userId?: number
  userName: string
}


const loading = ref(false)
const saving = ref(false)
const tableData = ref<WorkTeam[]>([])
const teamTypeOptions = ref<TeamTypeOption[]>([])
const teamTypeLoading = ref(false)
const multipleSelection = ref<WorkTeam[]>([])

const pagination = reactive({
  pageindex: 1,
  pagesize: 10,
  totalCount: 0
})

const searchForm = reactive({
  name: '',
  status: '',
  typeid: undefined as undefined | number
})

const statusOptions = [
  { label: '正常', value: '正常' },
  { label: '异常', value: '异常' }
]

const dialogVisible = ref(false)
const dialogTitle = ref('新增班组')
const dialogMode = ref<'create' | 'edit'>('create')
const dialogFormRef = ref<FormInstance>()
const dialogForm = reactive({
  id: 0,
  teamname: '',
  teamnumber: '',
  teamtypeid: undefined as undefined | number,
  fzr: '',
  status: '',
  desc: ''
})

const dialogRules: FormRules = {
  teamname: [{ required: true, message: '请输入班组名称', trigger: 'blur' }],
  teamnumber: [{ required: true, message: '请输入班组编码', trigger: 'blur' }],
  teamtypeid: [
    { required: true, message: '请选择班组类型', trigger: 'change' }
  ],
  fzr: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const selectedIds = computed(() => multipleSelection.value.map(item => item.id))

const userDialogVisible = ref(false)
const organTree = ref<OrganNode[]>([])
const organTreeLoading = ref(false)
const selectedOrganIdForUser = ref<number | null>(null)
const userList = ref<UserItem[]>([])
const userListLoading = ref(false)
const userSearchKeyword = ref('')
const selectedUserName = ref('')

const filteredUserList = computed(() => {
  const keyword = userSearchKeyword.value.trim().toLowerCase()
  if (!keyword) return userList.value
  return userList.value.filter(user =>
    user.userName.toLowerCase().includes(keyword)
  )
})

const getStatusCode = (payload: any) => payload?.code ?? payload?.Code
const getPayloadData = <T = any>(payload: any): T =>
  (payload?.data ?? payload?.Data) as T
const getPayloadMsg = (payload: any): string =>
  payload?.msg ?? payload?.Msg ?? ''
const getTotalCount = (payload: any) =>
  payload?.totalCount ?? payload?.TotalCount ?? 0

const fetchTeams = async () => {
  loading.value = true
  try {
    const params = {
      pageindex: pagination.pageindex,
      pagesize: pagination.pagesize,
      name: searchForm.name || undefined,
      status: searchForm.status || undefined,
      typeid: searchForm.typeid || undefined
    }
    const { data } = await https.Reads.get("/Working/ShowWork", { params })
    if (getStatusCode(data) === 1) {
      tableData.value = getPayloadData(data) ?? []
      pagination.totalCount = getTotalCount(data)
    } else {
      ElMessage.error(getPayloadMsg(data) || '获取班组失败')
    }
  } catch (error: any) {
    console.error('fetchTeams error', error)
    ElMessage.error(error?.message || '获取班组失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const fetchTeamTypes = async () => {
  teamTypeLoading.value = true
  try {
    const { data } = await https.Reads.get("/Working/ShowWorktype", {
      params: { pageindex: 1, pagesize: 200 }
    })
    if (getStatusCode(data) === 1) {
      teamTypeOptions.value = getPayloadData(data) ?? []
    }
  } catch (error) {
    console.error('fetchTeamTypes error', error)
  } finally {
    teamTypeLoading.value = false
  }
}

const handleSearch = () => {
  pagination.pageindex = 1
  fetchTeams()
}

const handleReset = () => {
  searchForm.name = ''
  searchForm.status = ''
  searchForm.typeid = undefined
  pagination.pageindex = 1
  fetchTeams()
}

const handleSizeChange = (val: number) => {
  pagination.pagesize = val
  pagination.pageindex = 1
  fetchTeams()
}

const handlePageChange = (val: number) => {
  pagination.pageindex = val
  fetchTeams()
}

const handleSelectionChange = (rows: WorkTeam[]) => {
  multipleSelection.value = rows
}

const resetDialogForm = () => {
  dialogForm.id = 0
  dialogForm.teamname = ''
  dialogForm.teamnumber = ''
  dialogForm.teamtypeid = undefined
  dialogForm.fzr = ''
  dialogForm.status = ''
  dialogForm.desc = ''
  dialogFormRef.value?.clearValidate()
}

const openCreateDialog = () => {
  dialogMode.value = 'create'
  dialogTitle.value = '新增班组'
  resetDialogForm()
  dialogVisible.value = true
}

const openEditDialog = (row: WorkTeam) => {
  dialogMode.value = 'edit'
  dialogTitle.value = '编辑班组'
  Object.assign(dialogForm, row)
  dialogVisible.value = true
  dialogFormRef.value?.clearValidate()
}

const submitAdd = async () => {
  const payload = {
    teamname: dialogForm.teamname,
    teamnumber: dialogForm.teamnumber,
    teamtypeid: dialogForm.teamtypeid,
    fzr: dialogForm.fzr,
    status: dialogForm.status,
    desc: dialogForm.desc
  }
  const { data } = await https.Writes.post("/Working/AddTeam", payload)
  return data
}

const submitUpdate = async () => {
  const payload = {
    id: dialogForm.id,
    teamname: dialogForm.teamname,
    teamnumber: dialogForm.teamnumber,
    teamtypeid: dialogForm.teamtypeid,
    fzr: dialogForm.fzr,
    status: dialogForm.status,
    desc: dialogForm.desc
  }
  const { data } = await https.Writes.put("/Working/UpdateTeam", payload)
  return data
}

const handleSubmit = () => {
  dialogFormRef.value?.validate(async valid => {
    if (!valid) return
    saving.value = true
    try {
      const result =
        dialogMode.value === 'create' ? await submitAdd() : await submitUpdate()
      if (getStatusCode(result) === 1) {
        ElMessage.success(getPayloadMsg(result) || '操作成功')
        dialogVisible.value = false
        fetchTeams()
      } else {
        ElMessage.error(getPayloadMsg(result) || '操作失败')
      }
    } catch (error: any) {
      console.error('handleSubmit error', error)
      ElMessage.error(error?.message || '保存失败，请稍后重试')
    } finally {
      saving.value = false
    }
  })
}

const handleBatchDelete = async () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择需要删除的班组')
    return
  }
  try {
    await ElMessageBox.confirm(
      `确定删除选中的 ${selectedIds.value.length} 条班组数据吗？`,
      '提示',
      { type: 'warning' }
    )
    const { data } = await https.Writes.delete("/Working/DelAllTeam", {
      data: { ids: selectedIds.value }
    })
    if (getStatusCode(data) === 1) {
      ElMessage.success(getPayloadMsg(data) || '删除成功')
      fetchTeams()
    } else {
      ElMessage.error(getPayloadMsg(data) || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('handleBatchDelete error', error)
      ElMessage.error(error?.message || '删除失败，请稍后重试')
    }
  }
}

const fetchOrganTree = async () => {
  organTreeLoading.value = true
  try {
    const { data } = await https.Reads.get('/Organtion/Binds')
    if (getStatusCode(data) === 1) {
      organTree.value = getPayloadData<OrganNode[]>(data) ?? []
    } else {
      ElMessage.error(getPayloadMsg(data) || '获取组织结构失败')
    }
  } catch (error: any) {
    console.error('fetchOrganTree error', error)
    ElMessage.error(error?.message || '获取组织结构失败，请稍后重试')
  } finally {
    organTreeLoading.value = false
  }
}

const fetchOrganUsers = async (organId: number) => {
  userListLoading.value = true
  try {
    const { data } = await https.Reads.get('/RBAC/ShowOrganUser', {
      params: { organid: organId }
    })
    if (getStatusCode(data) === 1) {
      userList.value = getPayloadData<UserItem[]>(data) ?? []
    } else {
      userList.value = []
      ElMessage.error(getPayloadMsg(data) || '该组织无成员')
    }
  } catch (error: any) {
    console.error('fetchOrganUsers error', error)
    userList.value = []
    ElMessage.error(error?.message || '获取成员失败，请稍后重试')
  } finally {
    userListLoading.value = false
  }
}

const openUserDialog = async () => {
  if (!organTree.value.length) {
    await fetchOrganTree()
  }
  userDialogVisible.value = true
  selectedUserName.value = dialogForm.fzr
  userSearchKeyword.value = ''
  if (selectedOrganIdForUser.value) {
    fetchOrganUsers(selectedOrganIdForUser.value)
  }
}

const handleOrganNodeClick = (node: OrganNode) => {
  selectedOrganIdForUser.value = Number(node.value)
  fetchOrganUsers(Number(node.value))
}

const handleUserConfirm = () => {
  if (!selectedUserName.value) {
    ElMessage.warning('请选择负责人')
    return
  }
  dialogForm.fzr = selectedUserName.value
  userDialogVisible.value = false
}

const clearSelectedUser = () => {
  dialogForm.fzr = ''
  selectedUserName.value = ''
}

onMounted(() => {
  fetchTeams()
  fetchTeamTypes()
})
</script>

<style scoped>
.work-team-page {
  padding: 16px;
  background: #f5f7fa;
}

.filter-card {
  margin-bottom: 12px;
}

.table-toolbar {
  display: flex;
  justify-content: flex-start;
  gap: 12px;
  margin-bottom: 12px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.fzr-select-row {
  display: flex;
  align-items: center;
  width: 100%;
}

.user-picker {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.user-picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-users {
  display: flex;
  align-items: center;
  gap: 8px;
}

.selected-users .label {
  color: #666;
}

.selected-users .placeholder {
  color: #bbb;
}

.user-picker-body {
  display: grid;
  grid-template-columns: 240px 1fr;
  gap: 16px;
}

.user-picker-tree,
.user-picker-list {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 8px;
  height: 360px;
  box-sizing: border-box;
}

.user-radio-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
</style>
